<?php

namespace common\components;

use Yii;
use common\modules\admin\models\Admin;
use mdm\admin\components\Helper;
use yii\helpers\Url;
class RbacModule extends \mdm\admin\Module{

    public $allowUsers = [
        'admin'
    ];

    public $navbar = [
        ['label' => '返回', 'url' => ['/site/index']],
        //['label' => '系统用户', 'url' => ['user/index']],
        ['label' => '权限分配', 'url' => ['assignment/index']],
        ['label' => '角色列表', 'url' => ['role/index']],
        ['label' => '权限列表', 'url' => ['permission/index']],
        ['label' => '路由列表', 'url' => ['route/index']],
    ];
    public $layout = 'main';
    private $_viewPath = '@mdm/admin/views';

    public function init(){
        parent::init();
        $this->controllerNamespace = 'mdm\admin\controllers';
        if(!isset($this->controllerMap['assignment'])){
            $this->controllerMap['assignment'] = [
                'class'         => 'mdm\admin\controllers\AssignmentController',
                'searchClass'   => 'common\modules\admin\models\search\AdminSearch',
                'extraColumns'  => [
                    ['attribute' => 'deleted', 'value'=>function ($model, $key, $index, $column){
                        return Admin::$dropdownFields['deleted'][$model['deleted']];
                    },'filter'=>Admin::$dropdownFields['deleted']]
                ],
            ];
        }else{
            if(!isset($this->controllerMap['assignment']['class'])){
                $this->controllerMap['assignment']['class'] = 'mdm\admin\controllers\AssignmentController';
            }
        }
        if(!isset($this->controllerMap['user'])){
            $this->controllerMap['user'] = [
                'class'     => 'common\modules\admin\controllers\AdminController',
                'viewPath'  => '@common/modules/admin/views/admin'
            ];
        }else{
            if(!isset($this->controllerMap['assignment']['class'])){
                $this->controllerMap['assignment']['class'] = 'mdm\admin\controllers\AssignmentController';
            }
        }
    }
    public function beforeAction($action){
        if(parent::beforeAction($action)){
            if(Yii::$app->user->isGuest){
                Yii::$app->user->loginRequired();
                return false;
            }else{
                if($this->allowUsers && in_array(Yii::$app->user->identity->name, $this->allowUsers)){
                    return true;
                }
                if (Helper::checkRoute('/' . $action->getUniqueId(), Yii::$app->getRequest()->get(), Yii::$app->user)) {
                    return true;
                }
                throw new ForbiddenHttpException('无访问权限，请联系管理员添加权限');
            }
        }
        return false;
    }

    public function getViewPath(){
        if ($this->_viewPath === null) {
            $this->_viewPath = Yii::getAlias('@mdm/admin/views');
        }

        return $this->_viewPath;
    }
}